package com.xiaoyu.servlet;

import com.xiaoyu.dao.BaseDao;
import com.xiaoyu.pojo.Person;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class searchPerson extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String input = req.getParameter("input");
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        Object[] params = {input, input};
            try {
            conn = BaseDao.getConnection();
            String sql = "select * from contact where `name` like concat(?,'%') or `phone` like concat(?,'%');";
            pst = conn.prepareStatement(sql);
            rs = BaseDao.execute(conn, sql, params, rs , pst);
            ArrayList<Person> result = new ArrayList<Person>();
            while(rs.next()) {
                Person person = new Person();
                person.setID(rs.getInt("ID"));
                person.setAge(rs.getInt("age"));
                person.setName(rs.getString("name"));
                person.setSex(rs.getString("sex"));
                person.setPhone(rs.getString("phone"));
                result.add(person);
            }
            req.setAttribute("result", result);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            BaseDao.release(conn, pst, rs);
            req.getRequestDispatcher("search.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
